/******************************************************************************************************
Copyright (C) 2015 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************************/

/*globals mainWindow, nmr, qsTr, settings, Application, Dir, File, MnUi, FileDialog, MessageBox, ProgressDialog, SnrPeakCalculator, TextStream*/
/*jslint plusplus: true, continue:true, indent: 4*/

//////////START NON-INTERACTIVE GUI IMPLEMENTATION/////////
function SnrPeakCalculator_Viewer() {
	'use strict';

	var dialog, snrPeakCalculatorInstance, restorePage, retoreSelectedPages, showDialog, manageError, spectra, i, startNoiseXKey, endNoiseXKey, startNoiseYKey, endNoiseYKey,
		automaticNoiseKey, minimumPointsInRegionKey, startSignalXKey, endSignalXKey, startSignalYKey, endSignalYKey, cb1DKey, cb2DKey, generalDataFile, generalDataFileKey,
		swap, file, stream, thisObj, dataJSON, generalSettings, thereIs1DSpectrum, thereIs2DSpectrum, applyValue, parameters, logDetail, logLevel, progressDialog, swapValues;

	//Registry Entries
	startNoiseXKey = "SNR Peak Calculator/Start Noise X";
	endNoiseXKey = "SNR Peak Calculator/End Noise X";
	startNoiseYKey = "SNR Peak Calculator/Start Noise Y";
	endNoiseYKey = "SNR Peak Calculator/End Noise Y";
	automaticNoiseKey = "SNR Peak Calculator/Automatic Noise";
	minimumPointsInRegionKey = "SNR Peak Calculator/Minimum Points in Region";
	startSignalXKey = "SNR Peak Calculator/Start Signal X";
	endSignalXKey = "SNR Peak Calculator/End Signal X";
	startSignalYKey = "SNR Peak Calculator/Start Signal Y";
	endSignalYKey = "SNR Peak Calculator/End Signal Y";
	cb1DKey = "SNR Peak Calculator/1D spectrum";
	cb2DKey = "SNR Peak Calculator/2D spectrum";
	generalDataFileKey = "SNR Peak Calculator/Settings Folder";

	//Initialize vars
	thereIs1DSpectrum = false;
	thereIs2DSpectrum = false;
	applyValue = -1;
	parameters = {};
	logDetail = "";
	logLevel = 1;
	swap = false;
	swapValues = false;

	//--------------------FUNCTIONS-------------------------------
	function loadSettings() {

		var dataFile, thereIs2DSpectra, flagExit;

		dataFile = FileDialog.getOpenFileName("*.*", "Open data", generalDataFile);

		if (dataFile !== "") {
			//Get data from file
			file = new File(dataFile);
			generalDataFile = file.name;
			file.open(File.ReadOnly);
			stream = new TextStream(file);
			dataJSON = stream.readAll();
			thisObj = JSON.parse(dataJSON);
			stream.flush();
			file.close();
			generalSettings = thisObj;
			flagExit = false;

			//Set data using the file managing the dimensions properly
			thereIs2DSpectra = SnrPeakCalculator.thereIsSelected1D2DSpectrum(true);
			if (!SnrPeakCalculator.thereIsSelected1D2DSpectrum(false) && generalSettings.rb1D) {
				MessageBox.critical("Settings for 2D spectrum are required");
				flagExit = true;
			} else if (thereIs2DSpectra && generalSettings.rb1D) {
				dialog.widgets.sbInputNoiseStartY.value = generalSettings.sbInputNoiseStartX;
				dialog.widgets.sbInputNoiseEndY.value = generalSettings.sbInputNoiseEndX;
				dialog.widgets.sbInputSignalStartY.value = generalSettings.sbInputSignalStartX;
				dialog.widgets.sbInputSignalEndY.value = generalSettings.sbInputSignalEndX;
				SnrPeakCalculator_Viewer.disableEnable2DsnrPeakCalculator(false);
			} else if (generalSettings.rb1D) {
				dialog.widgets.sbInputNoiseStartX.value = generalSettings.sbInputNoiseStartX;
				dialog.widgets.sbInputNoiseEndX.value = generalSettings.sbInputNoiseEndX;
				dialog.widgets.sbInputSignalStartX.value = generalSettings.sbInputSignalStartX;
				dialog.widgets.sbInputSignalEndX.value = generalSettings.sbInputSignalEndX;
			} else if (thereIs2DSpectra && generalSettings.rb2D) {
				dialog.widgets.sbInputNoiseStartX.value = generalSettings.sbInputNoiseStartX;
				dialog.widgets.sbInputNoiseEndX.value = generalSettings.sbInputNoiseEndX;
				dialog.widgets.sbInputNoiseStartY.value = generalSettings.sbInputNoiseStartY;
				dialog.widgets.sbInputNoiseEndY.value = generalSettings.sbInputNoiseEndY;
				dialog.widgets.sbInputSignalStartX.value = generalSettings.sbInputSignalStartX;
				dialog.widgets.sbInputSignalEndX.value = generalSettings.sbInputSignalEndX;
				dialog.widgets.sbInputSignalStartY.value = generalSettings.sbInputSignalStartY;
				dialog.widgets.sbInputSignalEndY.value = generalSettings.sbInputSignalEndY;
				SnrPeakCalculator_Viewer.disableEnable2DsnrPeakCalculator(true);
			} else if (!thereIs2DSpectra && generalSettings.rb2D) {
				MessageBox.critical("Settings for 1D spectrum are required");
				flagExit = true;
			}

			if (flagExit) {
				return;
			}

			dialog.widgets.rb1D.checked = generalSettings.rb1D;
			dialog.widgets.rb2D.checked = generalSettings.rb2D;
			dialog.widgets.groupBoxAutomaticNoise.checked = generalSettings.groupBoxAutomaticNoise;
			dialog.widgets.sbMinimumPointsInRegion.value = generalSettings.sbMinimumPointsInRegion;

			if (dialog.widgets.rb1D.checked && dialog.widgets.groupBoxAutomaticNoise.enabled && dialog.widgets.groupBoxAutomaticNoise.checked) {
				dialog.widgets.groupBoxNoise.enabled = false;
			} else {
				dialog.widgets.groupBoxNoise.enabled = true;
			}
			if (dialog.widgets.rb2D.checked) {
				dialog.widgets.groupBoxAutomaticNoise.enabled = false;
			} else {
				dialog.widgets.groupBoxAutomaticNoise.enabled = true;
			}
		}
	}

	function saveSettings() {

		var thereIs2DSpectra, dataFile, myJSONText;

		dataFile = FileDialog.getSaveFileName("*.data", "Save data", generalDataFile);
		thereIs2DSpectra = SnrPeakCalculator.thereIsSelected1D2DSpectrum(true);

		//When the file is not empty we get the data and assign it.
		if (dataFile  !==  "") {
			generalSettings = {};
			generalSettings.sbInputNoiseStartX = dialog.widgets.sbInputNoiseStartX.value;
			generalSettings.sbInputNoiseEndX = dialog.widgets.sbInputNoiseEndX.value;
			generalSettings.sbInputNoiseStartY = dialog.widgets.sbInputNoiseStartY.value;
			generalSettings.sbInputNoiseEndY = dialog.widgets.sbInputNoiseEndY.value;
			generalSettings.groupBoxAutomaticNoise = dialog.widgets.groupBoxAutomaticNoise.checked;
			generalSettings.sbMinimumPointsInRegion = dialog.widgets.sbMinimumPointsInRegion.value;
			generalSettings.sbInputSignalStartX = dialog.widgets.sbInputSignalStartX.value;
			generalSettings.sbInputSignalEndX = dialog.widgets.sbInputSignalEndX.value;
			generalSettings.sbInputSignalStartY = dialog.widgets.sbInputSignalStartY.value;
			generalSettings.sbInputSignalEndY = dialog.widgets.sbInputSignalEndY.value;
			generalSettings.rb1D = dialog.widgets.rb1D.checked;
			generalSettings.rb2D = dialog.widgets.rb2D.checked;

			if (dialog.widgets.rb1D.checked && thereIs2DSpectra) {
				generalSettings.sbInputNoiseStartX = dialog.widgets.sbInputNoiseStartY.value;
				generalSettings.sbInputNoiseEndX = dialog.widgets.sbInputNoiseEndY.value;
				generalSettings.sbInputSignalStartX = dialog.widgets.sbInputSignalStartY.value;
				generalSettings.sbInputSignalEndX = dialog.widgets.sbInputSignalEndY.value;
			}

			file = new File(dataFile);
			generalDataFile = file.name;
			settings.setValue(generalDataFileKey, generalDataFile);
			file.open(File.WriteOnly);
			stream = new TextStream(file);
			myJSONText = JSON.stringify(generalSettings);
			stream.write(myJSONText);
			stream.flush();
			file.close();
		}
	}

	function ManageError() {

		ManageError.prototype.writeErrorFocus = function (message, object, errorType) {
			var messageFinal;

			switch (errorType) {
			case "dirEmpty":
				messageFinal = message + " can not be empty. Please fill it and try again.";
				break;
			case "dirNotExist":
				messageFinal = message + " " + object.value + " does not exist.\nModify the path and try again.";
				break;
			case "fieldEmpty":
				messageFinal = message + " can not be empty. Please fill it and try again.";
				break;
			case "fileNotExist":
				messageFinal = message + " " + object.value + " does not exist.\nModify the path and try again.";
				break;
			case "mustNumber":
				messageFinal = message + " " + object.value + " must be a number.\nModify it and try again.";
				break;
			default:
				messageFinal = "Undefined error about " + message;
				break;
			}

			MessageBox.warning(messageFinal, MessageBox.Ok);
			object.setFocus();
		};
	}

	SnrPeakCalculator_Viewer.hideShow2DsnrPeakCalculator = function (aAction) {

		//Manage visibilty about signal Y axis components if spectrum 1s 2D
		dialog.widgets.lbNoiseF1.visible = aAction;
		dialog.widgets.lbNoiseF2.visible = aAction;
		dialog.widgets.lbSignalF1.visible = aAction;
		dialog.widgets.lbSignalF2.visible = aAction;

		//Manage visibilty noise Y axis components if spectrum is 2D;
		dialog.widgets.lbInputNoiseStartY.visible = aAction;
		dialog.widgets.sbInputNoiseStartY.visible = aAction;
		dialog.widgets.lbInputNoiseEndY.visible = aAction;
		dialog.widgets.sbInputNoiseEndY.visible = aAction;
		dialog.widgets.lbPPMNoiseY.visible = aAction;

		//Manage visibilty signal Y axis components if spectrum is 2D;
		dialog.widgets.lbInputSignalStartY.visible = aAction;
		dialog.widgets.sbInputSignalStartY.visible = aAction;
		dialog.widgets.lbInputSignalEndY.visible = aAction;
		dialog.widgets.sbInputSignalEndY.visible = aAction;
		dialog.widgets.lbPPMSignalY.visible = aAction;
	};

	SnrPeakCalculator_Viewer.disableEnable2DsnrPeakCalculator = function (aAction) {

		//Enable, disable noise X axis components;
		dialog.widgets.lbNoiseF2.enabled = aAction;
		dialog.widgets.lbInputNoiseStartX.enabled = aAction;
		dialog.widgets.sbInputNoiseStartX.enabled = aAction;
		dialog.widgets.lbInputNoiseEndX.enabled = aAction;
		dialog.widgets.sbInputNoiseEndX.enabled = aAction;
		dialog.widgets.lbPPMNoiseX.enabled = aAction;

		//Enable, disable signal X axis components;
		dialog.widgets.lbSignalF2.enabled = aAction;
		dialog.widgets.lbInputSignalStartX.enabled = aAction;
		dialog.widgets.sbInputSignalStartX.enabled = aAction;
		dialog.widgets.lbInputSignalEndX.enabled = aAction;
		dialog.widgets.sbInputSignalEndX.enabled = aAction;
		dialog.widgets.lbPPMSignalX.enabled = aAction;
	};

	SnrPeakCalculator_Viewer.swapF2andF1Values = function (aType) {

		var aux1, aux2, aux3, aux4;

		if (aType) {
			aux1 = dialog.widgets.sbInputNoiseStartX.value;
			aux2 = dialog.widgets.sbInputNoiseEndX.value;
			aux3 = dialog.widgets.sbInputSignalStartX.value;
			aux4 = dialog.widgets.sbInputSignalEndX.value;
			dialog.widgets.sbInputNoiseStartX.value = dialog.widgets.sbInputNoiseStartY.value;
			dialog.widgets.sbInputNoiseEndX.value = dialog.widgets.sbInputNoiseEndY.value;
			dialog.widgets.sbInputSignalStartX.value = dialog.widgets.sbInputSignalStartY.value;
			dialog.widgets.sbInputSignalEndX.value = dialog.widgets.sbInputSignalEndY.value;
			dialog.widgets.sbInputNoiseStartY.value = aux1;
			dialog.widgets.sbInputNoiseEndY.value = aux2;
			dialog.widgets.sbInputSignalStartY.value = aux3;
			dialog.widgets.sbInputSignalEndY.value = aux4;
		} else {
			aux1 = dialog.widgets.sbInputNoiseStartY.value;
			aux2 = dialog.widgets.sbInputNoiseEndY.value;
			aux3 = dialog.widgets.sbInputSignalStartY.value;
			aux4 = dialog.widgets.sbInputSignalEndY.value;
			dialog.widgets.sbInputNoiseStartY.value = dialog.widgets.sbInputNoiseStartX.value;
			dialog.widgets.sbInputNoiseEndY.value = dialog.widgets.sbInputNoiseEndX.value;
			dialog.widgets.sbInputSignalStartY.value = dialog.widgets.sbInputSignalStartX.value;
			dialog.widgets.sbInputSignalEndY.value = dialog.widgets.sbInputSignalEndX.value;
			dialog.widgets.sbInputNoiseStartX.value = aux1;
			dialog.widgets.sbInputNoiseEndX.value = aux2;
			dialog.widgets.sbInputSignalStartX.value = aux3;
			dialog.widgets.sbInputSignalEndX.value = aux4;
		}
	};

	if (mainWindow.activeDocument.itemCount("NMR Spectrum") === 0) {
		MessageBox.warning("An NMR spectrum is required to perform the analysis");
		return;
	}

	//Check if there is a 1D or a 2D selected spectrum, leaving the selections and curPage where is it before the checking.
	//In thereIsSelected1D2DSpectrum argument false look for a 1D spectrum and true look for 2D
	restorePage =  mainWindow.activeDocument.curPage();
	retoreSelectedPages = mainWindow.activeDocument.selectedPages();
	thereIs1DSpectrum = SnrPeakCalculator.thereIsSelected1D2DSpectrum(false);
	thereIs2DSpectrum = SnrPeakCalculator.thereIsSelected1D2DSpectrum(true);

	//By restoring the selected pages we lost the current item selected if the current page doesn't belong to the selection
	//We could restore the CurrentPageItemSelected but we lost the retoreSelectedPages
	mainWindow.activeDocument.setCurPage(restorePage);
	mainWindow.activeDocument.setSelectedPages(retoreSelectedPages);
	mainWindow.activeDocument.update();

	//Load dialog from .ui file
	dialog = Application.loadUiFile('ricares:SnrPeakCalculator_Viewer.ui');
	dialog.widgets.groupBoxApply.visible = false;

	//Load registy information
	dialog.widgets.sbInputNoiseStartX.value = settings.value(startNoiseXKey, dialog.widgets.sbInputNoiseStartX.value);
	dialog.widgets.sbInputNoiseEndX.value = settings.value(endNoiseXKey, dialog.widgets.sbInputNoiseEndX.value);
	dialog.widgets.sbInputNoiseStartY.value = settings.value(startNoiseYKey, dialog.widgets.sbInputNoiseStartY.value);
	dialog.widgets.sbInputNoiseEndY.value = settings.value(endNoiseYKey, dialog.widgets.sbInputNoiseEndY.value);
	dialog.widgets.sbInputSignalStartX.value = settings.value(startSignalXKey, dialog.widgets.sbInputSignalStartX.value);
	dialog.widgets.sbInputSignalEndX.value = settings.value(endSignalXKey, dialog.widgets.sbInputSignalEndX.value);
	dialog.widgets.sbInputSignalStartY.value = settings.value(startSignalYKey, dialog.widgets.sbInputSignalStartY.value);
	dialog.widgets.sbInputSignalEndY.value = settings.value(endSignalYKey, dialog.widgets.sbInputSignalEndY.value);
	dialog.widgets.rb1D.checked = settings.value(cb1DKey, true);
	dialog.widgets.rb2D.checked = settings.value(cb2DKey, false);
	dialog.widgets.groupBoxAutomaticNoise.checked = settings.value(automaticNoiseKey, dialog.widgets.groupBoxAutomaticNoise.checked);
	dialog.widgets.sbMinimumPointsInRegion.value = settings.value(minimumPointsInRegionKey, dialog.widgets.sbMinimumPointsInRegion.value);

	generalDataFile = settings.value(generalDataFileKey, Dir.home() + "/SnrPeakCalculator.data");

	//Hide radio buttons and Y axis if there isn't at least a 2D spectrum
	dialog.widgets.rb1D.checked = false;
	dialog.widgets.rb2D.checked = false;
	if (thereIs2DSpectrum && thereIs1DSpectrum) {
		SnrPeakCalculator_Viewer.hideShow2DsnrPeakCalculator(true);
		dialog.widgets.groupBoxApply.visible = true;
		if (nmr.activeSpectrum().dimCount === 2) {
			dialog.widgets.rb2D.checked = true;
			swap = false;
		} else {
			dialog.widgets.rb1D.checked = true;
			SnrPeakCalculator_Viewer.disableEnable2DsnrPeakCalculator(false);
			swap = true;
		}
	} else if (thereIs2DSpectrum) {
		SnrPeakCalculator_Viewer.hideShow2DsnrPeakCalculator(true);
		dialog.widgets.rb2D.checked = true;
	} else if (thereIs1DSpectrum) {
		SnrPeakCalculator_Viewer.hideShow2DsnrPeakCalculator(false);
		SnrPeakCalculator_Viewer.swapF2andF1Values(false);
		swapValues = true;
		swap = true;
		dialog.widgets.rb1D.checked = true;
	} else {
		MessageBox.warning("An NMR dimension is required");
	}

	//-------------------HANDLERS-------------------------------

	//Buttons Management
	dialog.widgets.tbLoadSettings.clicked.connect(loadSettings);
	dialog.widgets.tbSaveSettings.clicked.connect(saveSettings);

	//Radio Buttons Management
	dialog.widgets.rb1D.clicked.connect(dialog, function () {
		SnrPeakCalculator_Viewer.disableEnable2DsnrPeakCalculator(false);
		dialog.widgets.groupBoxAutomaticNoise.enabled = true;
		dialog.widgets.groupBoxNoise.enabled = true;
		swap = true;
	});
	dialog.widgets.rb2D.clicked.connect(dialog, function () {
		SnrPeakCalculator_Viewer.disableEnable2DsnrPeakCalculator(true);
		dialog.widgets.groupBoxAutomaticNoise.enabled = false;
		dialog.widgets.groupBoxNoise.enabled = true;
		swap = false;
	});

	//The exec() print windows. This means we need to have already loaded the previous signal which manage events thanks to connected method.
	dialog.show();
	showDialog = true;
	manageError = new ManageError();

	if (dialog.widgets.rb1D.checked && dialog.widgets.groupBoxAutomaticNoise.enabled && dialog.widgets.groupBoxAutomaticNoise.checked) {
		dialog.widgets.groupBoxNoise.enabled = false;
	} else {
		dialog.widgets.groupBoxNoise.enabled = true;
	}
	if (dialog.widgets.rb2D.checked) {
		dialog.widgets.groupBoxAutomaticNoise.enabled = false;
	} else {
		dialog.widgets.groupBoxAutomaticNoise.enabled = true;
	}

	while (showDialog) {
		//Check if cancle button is pulsed by user
		if (!dialog.exec()) {
			return;
		}

		//Manage 1D errors
		if (dialog.widgets.rb1D.checked || dialog.widgets.rb2D.checked) {
			if (!dialog.widgets.groupBoxAutomaticNoise.checked) {
				if (dialog.widgets.sbInputNoiseStartX.value === "") {
					manageError.writeErrorFocus("Noise Start X", dialog.widgets.sbInputNoiseStartX, "fieldEmpty");
					continue;
				}
				if (isNaN(dialog.widgets.sbInputNoiseStartX.value)) {
					manageError.writeErrorFocus("Noise Start X", dialog.widgets.sbInputNoiseStartX, "mustNumber");
					continue;
				}
				if (dialog.widgets.sbInputNoiseEndX.value === "") {
					manageError.writeErrorFocus("Noise End X", dialog.widgets.sbInputNoiseEndX, "fieldEmpty");
					continue;
				}
				if (isNaN(dialog.widgets.sbInputNoiseEndX.value)) {
					manageError.writeErrorFocus("Noise End X", dialog.widgets.sbInputNoiseEndX, "mustNumber");
					continue;
				}
			}
			if (dialog.widgets.sbInputSignalStartX.value === "") {
				manageError.writeErrorFocus("Signal Start X", dialog.widgets.sbInputSignalStartX, "fieldEmpty");
				continue;
			}
			if (isNaN(dialog.widgets.sbInputSignalStartX.value)) {
				manageError.writeErrorFocus("Signal Start X", dialog.widgets.sbInputSignalStartX, "mustNumber");
				continue;
			}
			if (dialog.widgets.sbInputSignalEndX.value === "") {
				manageError.writeErrorFocus("Signal End X", dialog.widgets.sbInputSignalEndX, "fieldEmpty");
				continue;
			}
			if (isNaN(dialog.widgets.sbInputSignalEndX.value)) {
				manageError.writeErrorFocus("Signal End X", dialog.widgets.sbInputSignalEndX, "mustNumber");
				continue;
			}
		}

		//Manage 2D errors
		if (dialog.widgets.rb2D.checked) {
			if (!dialog.widgets.groupBoxAutomaticNoise.checked) {
				if (dialog.widgets.sbInputNoiseStartY.value === "") {
					manageError.writeErrorFocus("Noise Start Y", dialog.widgets.sbInputNoiseStartY, "fieldEmpty");
					continue;
				}
				if (isNaN(dialog.widgets.sbInputNoiseStartY.value)) {
					manageError.writeErrorFocus("Noise Start Y", dialog.widgets.sbInputNoiseStartY, "mustNumber");
					continue;
				}
				if (dialog.widgets.sbInputNoiseEndY.value === "") {
					manageError.writeErrorFocus("Noise End Y", dialog.widgets.sbInputNoiseEndY, "fieldEmpty");
					continue;
				}
				if (isNaN(dialog.widgets.sbInputNoiseEndY.value)) {
					manageError.writeErrorFocus("Noise End Y", dialog.widgets.sbInputNoiseEndY, "mustNumber");
					continue;
				}
			}
			if (dialog.widgets.sbInputSignalStartY.value === "") {
				manageError.writeErrorFocus("Signal Start Y", dialog.widgets.sbInputSignalStartY, "fieldEmpty");
				continue;
			}
			if (isNaN(dialog.widgets.sbInputSignalStartY.value)) {
				manageError.writeErrorFocus("Signal Start Y", dialog.widgets.sbInputSignalStartY, "mustNumber");
				continue;
			}
			if (dialog.widgets.sbInputSignalEndY.value === "") {
				manageError.writeErrorFocus("Signal End Y", dialog.widgets.sbInputSignalEndY, "fieldEmpty");
				continue;
			}
			if (isNaN(dialog.widgets.sbInputSignalEndY.value)) {
				manageError.writeErrorFocus("Signal End Y", dialog.widgets.sbInputSignalEndY, "mustNumber");
				continue;
			}
		}

		//At least the user must check a radio button
		if ((!dialog.widgets.rb1D.checked) && (!dialog.widgets.rb2D.checked)) {
			MessageBox.warning("An NMR dimension is required");
			dialog.widgets.rb1D.setFocus();
			continue;
		}

		//Manage the kind of spectrum to apply the calculating
		if (dialog.widgets.rb1D.checked && dialog.widgets.rb2D.checked) {
			applyValue = 2;
		} else {
			if (dialog.widgets.rb1D.checked) {
				applyValue = 0;
			} else {
				applyValue = 1;
			}
		}

		//Manage the not coherent posibilities by using the radio buttons
		if (applyValue === 0 && !thereIs1DSpectrum) {
			MessageBox.warning("No 1D spectra selected");
			continue;
		}
		if (applyValue === 1 && !thereIs2DSpectrum) {
			MessageBox.warning("No 2D spectra selected");
			continue;
		}
		if (applyValue === 2 && !thereIs1DSpectrum && !thereIs2DSpectrum) {
			MessageBox.warning("No spectra selected");
			continue;
		}
		showDialog = false;
	}

	//Undo the swapping to save the data
	if (swapValues) {
		SnrPeakCalculator_Viewer.swapF2andF1Values(false);
	}

	//Save Registry Entries
	settings.setValue(startNoiseXKey, dialog.widgets.sbInputNoiseStartX.value);
	settings.setValue(endNoiseXKey, dialog.widgets.sbInputNoiseEndX.value);
	settings.setValue(startNoiseYKey, dialog.widgets.sbInputNoiseStartY.value);
	settings.setValue(endNoiseYKey, dialog.widgets.sbInputNoiseEndY.value);
	settings.setValue(automaticNoiseKey, dialog.widgets.groupBoxAutomaticNoise.checked);
	settings.setValue(minimumPointsInRegionKey, dialog.widgets.sbMinimumPointsInRegion.value);
	settings.setValue(startSignalXKey, dialog.widgets.sbInputSignalStartX.value);
	settings.setValue(endSignalXKey, dialog.widgets.sbInputSignalEndX.value);
	settings.setValue(startSignalYKey, dialog.widgets.sbInputSignalStartY.value);
	settings.setValue(endSignalYKey, dialog.widgets.sbInputSignalEndY.value);
	settings.setValue(cb1DKey, dialog.widgets.rb1D.checked);
	settings.setValue(cb2DKey, dialog.widgets.rb2D.checked);

	//Set parameters to engine by using an object sent pattern
	if (!swap) {
		parameters.noiseStartX = dialog.widgets.sbInputNoiseStartX.value;
		parameters.noiseEndX = dialog.widgets.sbInputNoiseEndX.value;
		parameters.noiseStartY = dialog.widgets.sbInputNoiseStartY.value;
		parameters.noiseEndY = dialog.widgets.sbInputNoiseEndY.value;
		parameters.signalStartX = dialog.widgets.sbInputSignalStartX.value;
		parameters.signalEndX = dialog.widgets.sbInputSignalEndX.value;
		parameters.signalStartY = dialog.widgets.sbInputSignalStartY.value;
		parameters.signalEndY = dialog.widgets.sbInputSignalEndY.value;
	} else {
		parameters.noiseStartX = dialog.widgets.sbInputNoiseStartY.value;
		parameters.noiseEndX = dialog.widgets.sbInputNoiseEndY.value;
		parameters.noiseStartY = dialog.widgets.sbInputNoiseStartX.value;
		parameters.noiseEndY = dialog.widgets.sbInputNoiseEndX.value;
		parameters.signalStartX = dialog.widgets.sbInputSignalStartY.value;
		parameters.signalEndX = dialog.widgets.sbInputSignalEndY.value;
		parameters.signalStartY = dialog.widgets.sbInputSignalStartX.value;
		parameters.signalEndY = dialog.widgets.sbInputSignalEndX.value;
	}
	if (dialog.widgets.rb1D.checked && dialog.widgets.groupBoxAutomaticNoise.enabled && dialog.widgets.groupBoxAutomaticNoise.checked) {
		parameters.automaticNoise = dialog.widgets.groupBoxAutomaticNoise.checked;
		parameters.minimumPointsInRegionForAutomaticNoise = dialog.widgets.sbMinimumPointsInRegion.value;
	}
	parameters.apply = applyValue;	//0: 1D, 1: 2D, 2: 1D and 2D
	parameters.logLevel = logLevel; //0: INFO; 1: ERROR; 2: INFO & ERROR
	parameters.deleteOldPeaks = true;
	parameters.viewer = true;

	//Get spectra to process
	spectra = SnrPeakCalculator.getAllSelectedSpectra();
	if (spectra === undefined) {
		MessageBox.warning("No spectra found in your selection. Make a new selection and try again");
	} else {

		//Create a progress bar to informate the user
		progressDialog = new ProgressDialog();
		progressDialog.visible = true;
		progressDialog.minimum = 0;
		progressDialog.maximum = 100;
		progressDialog.value = 0;

		//Iterate through all spectra and call to the snrPeak engine
		for (i = 0; i < spectra.length && !progressDialog.wasCanceled; i++) {
			parameters.spectrum = spectra[i];
			progressDialog.labelText = "Calculating SNR Peaks for " + parameters.spectrum.experimentType + "_" + parameters.spectrum.getParam("Pulse Sequence") + " spectrum";
			progressDialog.value = ((i + 1) / spectra.length) * 100;
			mainWindow.processEvents();
			snrPeakCalculatorInstance = new SnrPeakCalculator(parameters);
			if (snrPeakCalculatorInstance.status && !progressDialog.wasCanceled) {
				snrPeakCalculatorInstance.process();
				logDetail += snrPeakCalculatorInstance.logDetail;
			}
		}
		//Close progress bar
		progressDialog.visible = false;
		progressDialog.close();

		if (logDetail !== undefined && logDetail !== "" && logLevel === 1) {
			MessageBox.critical(logDetail);
		} else if (logDetail !== undefined && logDetail !== "" && logLevel === 0) {
			MessageBox.information(logDetail);
		}
	}
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_SNRPeakCalculator_Viewer = SnrPeakCalculator_Viewer;
}
